// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class Daojishi extends cc.Component {

    lab: cc.Label = null;
    onLoad() {
        this.lab = this.getComponent(cc.Label);
        if (this.lab == null) {
            console.error("倒计时节点 没有找到 cc.label : " + this.node.name);
        }
    }

    start() {

    }

    last_str = "";
    update(dt) {
        let str = "";
        switch (this.type) {
            case 2:
                str = this.get_time_str_2();
                break;
            case 3:
                str = this.get_time_str_3();
                break;
            default:
                break;
        }
        if (str != this.last_str) {
            this.last_str = str;
            this.lab.string = str;
            if (str == "00:00" || str == "00:00:00") {
                this.end_event && this.end_event();
            }
        }
    }

    end_time = 0; ////// 结束时间
    end_event: Function = null;
    type: 2 | 3 = 3; //// 显示 分钟秒 或者 小时分钟秒
    //////////// 设置当前时间
    set_time(t: number, end_event: Function = null) {        
        this.end_time = Date.now() + t * 1000;

        this.end_event = end_event;
    }

    get_time_str_2(): string {
        let m = this.end_time - Date.now();
        if (m <= 0) {
            return "00:00";
        } else {
            let m_s = Math.floor(m / 1000);
            let m_m = Math.floor(m_s / 60);
            return (m_m < 10 ? "0" : "") + m_m + ":" + (m_s % 60 < 10 ? "0" : "") + m_s % 60;
        }
    }

    get_time_str_3(): string {
        let m = this.end_time - Date.now();
        if (m <= 0) {
            return "00:00:00";
        } else {
            let m_s = Math.floor(m / 1000);
            let m_m = Math.floor(m_s / 60);
            let m_h = Math.floor(m_m / 60);
            return (m_h < 10 ? "0" : "") + m_h + ":" + (m_m % 60 < 10 ? "0" : "") + m_m % 60 + ":" + (m_s % 60 < 10 ? "0" : "") + m_s % 60;
        }
    }

}
